#!/bin/bash
#
# Copyright (c) 2012 BidiX (http://bidix.info)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
 
#
# notewikiapp_edit command
# 	edit an article
# 
# use CocoaDialog : http://mstratman.github.com/cocoadialog/
# use Textmate : http://macromates.com
# use Platypus : http://sveinbjorn.org/platypus/
#
# 	$1 : article_name
#
# if no parameter 
#	open a COCOADIALOG to get article name
#
# CLIENT Get article_name from APP
# open in EDITOR for edition
# when windows is closed
# CLIENT post article_name

source notewikiapp_edit.env 

function urlencode {
encoded_value=$(python -c "import urllib; print urllib.quote('''$1''')")
echo $encoded_value
}

if [[ "$1" == "" ]] 
	then
	rv=`$COCOADIALOG standard-inputbox --title "Article to edit" --no-newline \\
		--informative-text "article_name"`
	button_rv=`echo $rv | cut -b 1`
	name=`echo $rv | cut -b 3-`
	if [[ $button_rv == "1" ]]
		then
		article=$name
	else
		echo "No article name"
		exit 1
	fi
	else
	article=$1
fi
# tempfile
FILE=$(mktemp /tmp/notewiki.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1; }

echo "Get $article..."
$CLIENT 'GET' /$article.md > $FILE
echo "Got $article"

$EDITOR $FILE

title=`cat $FILE | grep 'Title:' | cut -b 8- `
tags=`cat $FILE | grep 'Tags:' | cut -b 7- `
text=`cat $FILE | grep -e 'Title:' -e 'Tags:' -v`

title=`urlencode "$title"`
tags=`urlencode "$tags"`
text=`urlencode "$text"`

echo "Post $article..."

$CLIENT 'POST' /$article "command=edit&name=$article&title=$title&tag=$tags&text=$text"

echo "Posted $article"

rm $FILE
